capture program drop construct_base_totallength
program define construct_base_totallength
* Arguments
* 1: input
* 2: output
* 3 4: left and right censoring
* 5: either whole for whole sample or sub for sub-periods, the difference being that 
* 6: country group to be considered
* summary statistics on druations are computed for the whole period only
clear 
g $product=0 
drop if $product==0 
save `2', replace 

local j=`j'+3
*local j=3
foreach i in `6' {
	use `1', clear
	keep if iso2=="`i'"
	save transaction_`i', replace

	use transaction_`i', clear
	tab iso2 
	drop if $product==0
	sort year month	
	id_group id_t "year month" // id_group does the same job as egen group (but work if we have millions of groups)
	sort iso2 buyer $product year month siren
	id_group id_sc "siren iso2" // id_group does the same job as egen group (but work if we have millions of groups)
	id_group id_b "iso2 buyer" // id_group does the same job as egen group (but work if we have millions of groups)
	id_group id_bp "iso2 buyer $product" // id_group does the same job as egen group (but work if we have millions of groups)
	id_group id_bs "id_bp id_s"	 // id_group does the same job as egen group (but work if we have millions of groups)
	sort id_bp id_t
	g date=year+(month-1)/12
	// length_bp defined as the difference between the first and the last months of a buyer's history
	* length of a continuous relationship 
	sort id_bs id_t
	by id_bs: g first=1 if _n==1
	by id_bs: g last=1 if _n==_N
	g _=date*first
	by id_bs: egen datefirst=mean(_)
	drop _
	g _=date*last	
	by id_bs: egen datelast=mean(_)
	drop _
	g length_total=(datelast-datefirst)*12+1
	// length_bps defined as the difference between the first and the last months of a continuous relationship

	
	*g firstyear_panel=substr(firstdate,1,4) //from where doesfirstdate come?? 
	*destring firstyear_panel, replace
	g firstyear_sample=floor(datefirst)
	`3' // drop all seller*buyer relationships that we do not observe from the start (treats left-censoring)
	`4' // drop all seller*buyer relationships starting two years before the end (treats right-censoring)
	drop datelast datefirst first last firstyear_sample // firstyear_panel
	compress
	collapse (mean) length_total export (sum) totx=export, by(id_bs $product iso2)
	append using `2'
	save `2', replace 
	erase transaction_`i'.dta
}
g _="`5'"
if _=="whole"{
	global endcountry=`j'
}
end
